<template>
  <view class="viewpoint">
    <!-- 头部 -->
    <view class="header" :style="{ paddingTop: safeAreaInsets!.top + 'px'}">
      <!-- 返回 -->
      <view class="back" @tap="back"><text class="iconfont icon-xiangzuo"></text></view>
      <!-- 搜索框 -->
      <view class="search">
        <!-- 输入框 -->
        <view class="input-item">
          <view class="icon"> <text class="iconfont icon-sousuo"></text></view>
          <view class="search_input">
            <input
              v-model="SearchForm.keyword"
              placeholder="请输入关键字"
              placeholder-class="input-placeholder"
              @input="Search"
              :focus="true"
              @focus="Focus"
            />
          </view>
          <view class="icon_1" @tap="clearword"> <text class="iconfont icon-qingchu"></text></view>
        </view>
      </view>
      <!-- 搜索按钮 -->
      <view class="publish" @tap="SearchKeyword">
        <text>搜索</text>
      </view>
    </view>
    <!-- 关键字列表 -->
    <view class="keyList" v-show="conversion == 2">
      <scroll-view scroll-y>
        <view
          class="List_item"
          v-for="item in heightLight"
          :key="item.newsId"
          @tap="clickKeyword(item)"
        >
          <view><text class="iconfont icon-sousuo"></text></view>
          <view class="item"><p v-html="item.title"></p></view>
        </view>
      </scroll-view>
    </view>
    <!-- 搜索内容 -->
    <view class="SearchContain" v-show="conversion == 3">
      <scroll-view scroll-y v-if="newsList_c.length != 0">
        <view class="contain" @tap="clickDai(item)" v-for="item in newsList_c" :key="item.newsId">
          <!-- 标题 -->
          <view class="title" v-html="item.title"></view>
          <!-- 内容 -->
          <view class="contain_item" v-html="item.content"></view>
          <!-- 作者 -->
          <view class="user">
            <image class="user_avatar" :src="item.avatar" />
            <view class="username">{{ item.username }}</view>
          </view>
        </view>
      </scroll-view>
      <view v-else style="color: #a09e9e; text-align: center;margin-top: 20rpx;">~暂无内容~</view>
    </view>
    <!-- 默认状态 -->
    <view class="defualt" v-show="conversion == 1">
      <scroll-view scroll-y>
        <!-- 搜索历史 -->
        <view class="history" v-show="MemberStore.history.length != 0">
          <view class="history-nav">
            <text>搜索历史</text><text class="iconfont icon-lajixiang" @tap="clearhistory"></text>
          </view>
          <view class="history-contain">
            <template v-for="(item, index) in MemberStore.history" :key="item.newsId">
              <view @tap="clickhistory(item)" v-if="index % 2 == 0" class="history-iteml">{{
                item.title
              }}</view>
              <view @tap="clickhistory(item)" v-else class="history-itemr">{{ item.title }}</view>
            </template>
          </view>
        </view>
        <!-- 热点新闻 -->
        <view class="guess">
          <view class="guess-nav">
            <text>猜你喜欢</text>
          </view>
          <view class="guess-contain">
            <template v-for="(item, index) in hotList" :key="item.newsId">
              <view @tap="clickHot(item)" v-if="index % 2 == 0" class="guess-iteml">{{
                item.title
              }}</view>
              <view @tap="clickHot(item)" v-else class="guess-itemr">{{ item.title }}</view>
            </template>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { SearchAPI, hotAPI } from '@/services/news'
import type { hotItem } from '@/types/news'
import type { newsItem } from '@/types/index'
import { onLoad } from '@dcloudio/uni-app'
import { useMemberStore } from '@/stores/index'
const SearchForm = ref({
  keyword: '',
  page: 1,
  pageSize: 100000,
})
const MemberStore = useMemberStore()
//切换
const conversion = ref(1) //1为默认，2为列表，3为内容
//搜索新闻
let timer = ref<null | number>(null)
const newsList = ref<newsItem[]>([])
const newsList_c = ref<newsItem[]>([])
const keywordList = ref<{ title: string; newsId: number }[]>([])
//输入关键字触发
const Search = async () => {
  conversion.value = 2
  if (SearchForm.value.keyword == '') {
    conversion.value = 1
    keywordList.value = []
    return
  }
  debounce(searchHandle, 500)
}
//发起搜索请求
const searchHandle = async () => {
  keywordList.value = []
  const res = await SearchAPI(SearchForm.value)
  newsList.value = res.data.newsList.list
  newsList.value?.forEach((item: newsItem) => {
    keywordList.value?.push({ title: item.title, newsId: item.newsId! })
  })
}
//防抖函数
const debounce = (fn: Function, delay: number) => {
  timer.value && clearTimeout(timer.value)
  timer.value = setTimeout(fn, delay)
}
//计算关键字高亮
const heightLight = computed(() => {
  if (!SearchForm.value.keyword) {
    return (keywordList.value = [])
  }

  const regex = new RegExp('(' + escapeRegExp(SearchForm.value.keyword) + ')', 'gi')

  const highlightedList = keywordList.value.map((item: { title: string; newsId: number }) => {
    return {
      ...item,
      title: item.title.replace(regex, '<span class="highlight">$1</span>'),
    }
  })

  return highlightedList
})

function escapeRegExp(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
//点击列表
const clickKeyword = (item: { title: string; newsId: number }) => {
  item.title = item.title.replace(/<\/?[^>]+(>|$)/g, '')
  MemberStore.set_history(item) //存历史
  uni.navigateTo({ url: `/pages/detail/detail?newsId=${item.newsId}` })
}
//清除列表
const clearhistory = () => {
  MemberStore.clear_history()
}
//热点搜索
const hotList = ref<hotItem[]>([])
const getHot = async () => {
  const res = await hotAPI()
  hotList.value = res.data
}
//点击搜索
const SearchKeyword = async () => {
  MemberStore.set_history({ title: SearchForm.value.keyword }) //存历史
  Function(SearchForm.value.keyword)
}
//函数封装
const Function = async (keyword: string) => {
  conversion.value = 3
  const regex = new RegExp('(' + escapeRegExp(keyword) + ')', 'gi')
  const res = await SearchAPI({ keyword: keyword, page: 1, pageSize: 10000 })
  newsList_c.value = res.data.newsList.list
  newsList_c.value.forEach((item: newsItem) => {
    item.content = item.content.replace(/<img\b[^>]*>/gi, '')
    item.title = item.title.replace(regex, '<span class="highlight">$1</span>')
  })
}
//点击历史
const clickhistory = (item: { title: string; newsId?: number }) => {
  SearchForm.value.keyword = item.title
  if (item.newsId) {
    MemberStore.set_history(item) //存历史
    uni.navigateTo({ url: `/pages/detail/detail?newsId=${item.newsId}` })
  } else {
    MemberStore.set_history({ title: item.title }) //存历史
    Function(item.title)
  }
}
//点击热点
const clickHot = (item: any) => {
  MemberStore.set_history({ title: item.title }) //存历史
  uni.navigateTo({ url: `/pages/detail/detail?newsId=${item.newsId}` })
}
//点击内容
const clickDai = (item: any) => {
  uni.navigateTo({ url: `/pages/detail/detail?newsId=${item.newsId}` })
}
//清除搜索关键字
const clearword = () => {
  SearchForm.value.keyword = ''
  conversion.value = 1
}
//获得焦点
const Focus = () => {
  Search()
}
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
//返回
const back = () => {
  uni.navigateBack()
}
onLoad(() => {
  getHot()
})
</script>

<style lang="scss">
page {
  height: 100%;
}
.viewpoint {
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    height: 160rpx;
    width: 100%;
    background-color: #f04142;
    padding: 0 10rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;
    .back {
      .iconfont {
        font-size: 50rpx;
        color: #fff;
      }
    }
    .search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 100%;
      .input-item {
        background-color: #fff;
        height: 70rpx;
        width: 500rpx;
        display: flex;
        border-radius: 10rpx;
        box-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.5);
        .icon {
          height: 100%;
          width: 70rpx;
          line-height: 70rpx;
          text-align: center;
          font-weight: bold;
          color: #ccc;
        }
        .icon_1 {
          height: 100%;
          width: 50rpx;
          line-height: 70rpx;
          text-align: center;
          padding-right: 5rpx;
          font-weight: bold;
          color: #ccc;
          .icon-qingchu {
            font-size: 32rpx;
          }
        }
        .search_input {
          flex: 1;
          color: #ccc;
          font-size: 32rpx;
          line-height: 70rpx;
          padding-right: 5rpx;
          input {
            height: 100%;
            color: #433e3e;
            .input-placeholder {
              color: #ccc;
            }
          }
        }
      }
    }
    .publish {
      width: 140rpx;
      height: 70rpx;
      background-color: #fff;
      border-radius: 60rpx;
      text-align: center;
      line-height: 70rpx;

      font-weight: bold;
      color: #f04142;
      text {
        color: #f04142;
        font-size: 32rpx;
      }
    }
  }
  .keyList {
    height: calc(100vh - 160rpx);
    padding: 0 10rpx;
    .List_item {
      height: 100rpx;
      width: 100%;
      line-height: 100rpx;
      border-bottom: 1rpx solid #e3e2e2;
      display: flex;
      .iconfont {
        color: #ccc;
        font-size: 36rpx;
        font-weight: bold;
      }
      .item {
        font-size: 36rpx;
        color: #000;
        margin-left: 10rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
  }
  .defualt {
    height: calc(100vh - 160rpx);
    padding: 20rpx 25rpx 0 25rpx;
    .history {
      padding-bottom: 30rpx;
      border-bottom: 1rpx solid #a09e9e;
      .history-nav {
        display: flex;
        justify-content: space-between;
        color: #a09e9e;
        font-size: 28rpx;
      }
      .history-contain {
        margin-top: 20rpx;
        display: flex;
        flex-wrap: wrap;

        .history-iteml,
        .history-itemr {
          width: 50%;
          margin: 10rpx 0;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          line-clamp: 1;
          -webkit-box-orient: vertical;
        }
        .history-iteml {
          border-right: 1rpx solid #3d3c3c;
          padding-right: 20rpx;
        }
        .history-itemr {
          padding-left: 20rpx;
        }
      }
      .iconfont {
        font-weight: bold;
      }
    }
    .guess {
      margin-top: 30rpx;
      .guess-nav {
        display: flex;
        justify-content: space-between;
        color: #a09e9e;
        font-size: 28rpx;
      }
      .guess-contain {
        margin-top: 20rpx;
        display: flex;
        flex-wrap: wrap;
        .guess-iteml,
        .guess-itemr {
          margin: 10rpx 0;
          width: 50%;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          line-clamp: 1;
          -webkit-box-orient: vertical;
        }
        .guess-iteml {
          border-right: 1rpx solid #3d3c3c;
          padding-right: 20rpx;
        }
        .guess-itemr {
          padding-left: 20rpx;
        }
      }
      .iconfont {
        font-weight: bold;
      }
    }
  }
  .SearchContain {
    height: calc(100vh - 160rpx);
    padding: 0 10rpx;
    background-color: #f0f0f0;
    .contain {
      height: 360rpx;
      width: 100%;
      margin-top: 20rpx;
      background-color: #fff;
      border-radius: 20rpx;
      box-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);
      padding: 20rpx;
      .title {
        height: 60rpx;
        color: #000;
        line-height: 60rpx;
        font-size: 40rpx;
        font-weight: bold;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        line-clamp: 1;
        -webkit-box-orient: vertical;
      }
      .contain_item {
        height: 205rpx; /* 设置元素的高度 */
        padding: 10rpx 0; /* 设置上下内边距为10rpx，左右内边距为0 */
        width: 100%; /* 设置元素的宽度为100% */
        overflow: hidden; /* 隐藏元素溢出的内容 */
        display: -webkit-box; /* 使用弹性盒子布局 */
        -webkit-box-orient: vertical; /* 设置弹性盒子的方向为垂直 */
        word-wrap: break-word; /* 文本在需要时自动换行，不会超出盒子宽度 */
        font-size: 32rpx;
        display: -webkit-box;
        -webkit-line-clamp: 5; /* 显示文本的行数，超过行数的部分会被隐藏 */
      }
      .user {
        width: 100%;
        height: 50rpx;
        display: flex;
        align-items: center;
        .user_avatar {
          width: 30rpx;
          height: 30rpx;
          border-radius: 30rpx;
        }
        .username {
          color: #9b9999;
          margin-left: 10rpx;
          font-size: 26rpx;
        }
      }
    }
  }
}
.highlight {
  color: #f04142;
}
</style>